#include<iostream>
#include<vector>
#include<memory>   
#include<string>
#include<algorithm>
using namespace std;

// 抽象组件类：文件系统中的元素（文件或文件夹）
class FileSystemComponent
{
public:
    virtual void showInfo(int indent = 0) = 0;                        // 显示文件/文件夹信息
    virtual void add(shared_ptr<FileSystemComponent> component) {}    // 仅文件夹可用
    virtual void remove(shared_ptr<FileSystemComponent> component) {} // 仅文件夹可用
    virtual ~FileSystemComponent() = default;
};

// 叶子节点：文件类
class File : public FileSystemComponent
{
    string name;

public:
    File(const string &n) : name(n) {}

    void showInfo(int indent = 0) override
    {
        cout << string(indent, ' ') << "File: " << name << endl;
    }
};

// 容器节点：文件夹类
class Folder : public FileSystemComponent
{
    string name;
    vector<shared_ptr<FileSystemComponent>> children;

public:
    Folder(const string &n) : name(n) {}

    void add(shared_ptr<FileSystemComponent> component) override
    {
        children.push_back(component);
    }
    void remove(shared_ptr<FileSystemComponent> component) override
    {
        // 1. 查找第一个匹配的元素（使用 std::find 算法）
        auto it = std::find(children.begin(), children.end(), component);

        // 2. 若找到，则删除该元素
        if (it != children.end())
        {
            children.erase(it); // 只删除第一个匹配的元素
        }
    }

    void showInfo(int indent = 0) override
    {
        cout << string(indent, ' ') << "Folder: " << name << endl;
        for (auto &child : children)
        {
            child->showInfo(indent + 4); // 缩进显示子元素
        }
    }
};

int main()
{
    // 创建文件
    shared_ptr<FileSystemComponent> file1 = make_shared<File>("file1.txt");
    shared_ptr<FileSystemComponent> file2 = make_shared<File>("file2.txt");
    shared_ptr<FileSystemComponent> file3 = make_shared<File>("file3.txt");
    shared_ptr<FileSystemComponent> file4 = make_shared<File>("file4.txt");
    // 创建文件夹
    shared_ptr<FileSystemComponent> folder1 = make_shared<Folder>("Folder1");
    shared_ptr<FileSystemComponent> folder2 = make_shared<Folder>("Folder2");
    shared_ptr<FileSystemComponent> folder3 = make_shared<Folder>("Folder3");
    shared_ptr<FileSystemComponent> folder4 = make_shared<Folder>("Folder4");

    // 添加文件到文件夹
    folder1->add(file1);
    folder1->add(folder4);
    folder1->add(file2);
    folder2->add(file3);
    folder4->add(file4);
    // 创建顶层文件夹
    shared_ptr<FileSystemComponent> rootFolder = make_shared<Folder>("RootFolder");
    rootFolder->add(folder1);
    rootFolder->add(folder2);
    rootFolder->add(folder3);
    // 显示整个文件系统结构
    cout << "=== File System ===" << endl;
    rootFolder->showInfo();

    // 移除文件
    folder1->remove(file2);

    cout << "\n=== After Removing file2.txt ===" << endl;
    rootFolder->showInfo();
    return 0;
}